package com.zcm.modules.cxf.services;

import com.aliyuncs.exceptions.ClientException;
import com.zcm.common.persistence.Page;
import com.zcm.common.utils.DateUtils;
import com.zcm.common.utils.IdGen;
import com.zcm.common.utils.StringUtils;
import com.zcm.modules.center.entity.CenterUser;
import com.zcm.modules.center.service.CenterService;
import com.zcm.modules.center.service.CenterUserService;
import com.zcm.modules.center.utils.NoticeUtils;
import com.zcm.modules.cms.entity.Article;
import com.zcm.modules.cms.entity.ArticleData;
import com.zcm.modules.cms.entity.Category;
import com.zcm.modules.cms.entity.Site;
import com.zcm.modules.cms.service.ArticleDataService;
import com.zcm.modules.cms.service.ArticleService;
import com.zcm.modules.cms.utils.CmsUtils;
import com.zcm.modules.cxf.entity.*;
import com.zcm.modules.cxf.service.CxfSessionService;
import com.zcm.modules.cxf.utils.CxfMsgCodeUtils;
import com.zcm.modules.cxf.utils.WebServiceHeaderUtil;
import com.zcm.modules.nbg.entity.*;
import com.zcm.modules.nbg.service.*;
import com.zcm.modules.sys.service.SystemService;
import com.zcm.modules.sys.utils.DictUtils;
import com.zcm.modules.xgb.entity.XgbBoardDown;
import com.zcm.modules.xgb.entity.XgbBoardStock;
import com.zcm.modules.xgb.entity.XgbBoomStock;
import com.zcm.modules.xgb.entity.XgbHistoryData;
import com.zcm.modules.xgb.service.XgbBoardDownService;
import com.zcm.modules.xgb.service.XgbBoardStockService;
import com.zcm.modules.xgb.service.XgbBoomStockService;
import com.zcm.modules.zhaocai.entity.Dadata;
import com.zcm.modules.zhaocai.service.ZcmKanpanDataService;
import com.zcm.modules.zhaocai.utils.DDDataUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.http.util.TextUtils;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;


//@WebService(endpointInterface = "com.zcm.modules.cxf.services.Duoduo")
public class DuoduoImpl implements Duoduo{

	@Autowired
	private XgbBoardStockService xgbBoardStockService;
	@Autowired
	private XgbBoomStockService xgbBoomStockService;
	@Autowired
	private XgbBoardDownService xgbBoardDownService;

	@Autowired
	private NbgBaseDataService nbgBaseDataService;
	@Autowired
	private NbgBeixuanService nbgBeixuanService;
	@Autowired
	private NbgFengkoService nbgFengkoService;
	@Autowired
	private NbgFengkoDetailService nbgFengkoDetailService;
	@Autowired
	private NbgJuechechiService nbgJuechechiService;
	@Autowired
	private NbgLtyaoguService nbgLtyaoguService;
	@Autowired
	private NbgZujichiService nbgZujichiService;

	@Autowired
	private CenterUserService centerUserService;
	@Autowired
	private ArticleService articleService;

	@Autowired
	private ZcmKanpanDataService zcmKanpanDataService;

	@Autowired
	private ArticleDataService articleDataService;
	@Autowired
	private CenterService centerService;
	@Autowired
	private CxfSessionService cxfSessionService;

	@Override
	public LogoutResponse logout(HeaderEntity header){
		WebServiceHeaderUtil.validateHeader(header);
		LogoutResponse response = new LogoutResponse();
		CxfSession session = cxfSessionService.getBySessionId(header.getSessionId());
		response.setResultCode(0);
		response.setMessage("登出成功！");
		cxfSessionService.delete(session);
		return response;
	}

	@Override
	public LoginResponse login(String loginName, String plainPassword) throws JSONException {
		String password =plainPassword;//centerService.getMD5(plainPassword);
		LoginResponse response = new LoginResponse();
		CenterUser centeruser = centerService.getUserByLoginName(loginName);
		if(centeruser==null){
			centeruser = centerService.getUserByMobile(loginName);
		}
		CxfSession session = cxfSessionService.getByUserName(loginName);
		if (session != null) {
            cxfSessionService.delete(session);
//			response.setResultCode(4);
//			response.setMessage("用户已经登陆，请误重复登陆！");
        }
		if (StringUtils.isBlank(loginName)) {
			response.setResultCode(1);
			response.setMessage("用户名不能为空");
		} else if (StringUtils.isBlank(plainPassword)) {
			response.setResultCode(2);
			response.setMessage("密码不能为空");
		} else if (null == centeruser || !SystemService.validatePassword(password,centeruser.getPassword())) {
			response.setResultCode(3);
			response.setMessage("用户名密码错误");
		} else {
            response.setResultCode( 0 );
            response.setMessage("登陆成功");
            response.setSessionId(IdGen.uuid());
            CxfSession cxfSession = new CxfSession();
            cxfSession.setUser(centeruser);
            cxfSession.setSessionId(response.getSessionId());
            cxfSessionService.save(cxfSession);
        }
        return response;

	}

	@Override
	public Dadata dddata(HeaderEntity header, String day){
		WebServiceHeaderUtil.validateHeader(header);
		Dadata dddata = getDData(day);
		return dddata;
	}

	private Dadata getDData(String day) {
		String toDay = DateUtils.getDate();
		Dadata dddata = new Dadata();
		Boolean isLatest = StringUtils.isNotEmpty(day) && !toDay.equals(day);
		if(isLatest){
			DDDataUtils.parseKpData( zcmKanpanDataService.getDataByDay("boardStockTask",day),dddata);
			DDDataUtils.parseKpData( zcmKanpanDataService.getDataByDay("boomStockTask",day),dddata);
			DDDataUtils.parseKpData( zcmKanpanDataService.getDataByDay("boardDownTask",day),dddata);
			DDDataUtils.parseKpData( zcmKanpanDataService.getDataByDay("boardPredayTask",day),dddata);
			DDDataUtils.parseKpData( zcmKanpanDataService.getDataByDay("multiStockTask",day),dddata);
			DDDataUtils.parseKpData( zcmKanpanDataService.getDataByDay("realTask",day),dddata);
			DDDataUtils.parseKpData( zcmKanpanDataService.getDataByDay("quoteChangeTask",day),dddata);
		}else{
			DDDataUtils.parseKpData( zcmKanpanDataService.getLatestData("boardStockTask"),dddata);
			DDDataUtils.parseKpData( zcmKanpanDataService.getLatestData("boomStockTask"),dddata);
			DDDataUtils.parseKpData( zcmKanpanDataService.getLatestData("boardDownTask"),dddata);
			DDDataUtils.parseKpData( zcmKanpanDataService.getLatestData("boardPredayTask"),dddata);
			DDDataUtils.parseKpData( zcmKanpanDataService.getLatestData("multiStockTask"),dddata);
			DDDataUtils.parseKpData( zcmKanpanDataService.getLatestData("realTask"),dddata);
			DDDataUtils.parseKpData( zcmKanpanDataService.getLatestData("quoteChangeTask"),dddata);
		}
		return dddata;
	}

	@Override
	public Dadata ddqsdx(HeaderEntity header, String day) {
		WebServiceHeaderUtil.validateHeaderWithoutSession(header);
		Dadata dddata = getDData(day);
		dddata.setLbggs(null);
		dddata.setYzbs(null);
		dddata.setSthsztb(null);
		dddata.setBzkbs(null);
//		dddata.setDtbs(null);
//		dddata.setQsgs(null);
//		dddata.setZrzts(null);
		return dddata;
	}

	@Override
    public CxfArticleListResponse ls_article(HeaderEntity header, int pageSize, int pageNo) {
        WebServiceHeaderUtil.validateHeader(header);
        CxfArticleListResponse response = new CxfArticleListResponse();


        Map<String,Object> map = new HashMap<String, Object>();
        String categoryId = DictUtils.getDictValue("zcm_article","zcm_config_catalog","");
        Category category1 = CmsUtils.getCategory(categoryId);
        if(category1 == null){
            throw new Fault(new Exception("服务端资讯配置错误."));
        }
        String siteId = CmsUtils.getCategory(categoryId).getSite().getId();

        Page<Article> page = new Page<Article>(pageNo,pageSize);
        Category category = new Category(categoryId, new Site(siteId));
        category.setParentIds(categoryId);
        Article article = new Article(category);
        article.setDelFlag(Article.DEL_FLAG_NORMAL);
        page = articleService.findPage(page, article, false);
        response.setTotal(page.getCount());
        response.setPageSize(pageSize);
        response.setPageNo(pageNo);
        response.setArticle(page.getList());
        return response;
    }

    @Override
    public CxfArticleDetailResponse show_atricle(HeaderEntity header, String id) {
        WebServiceHeaderUtil.validateHeader(header);
        ArticleData articleData = articleDataService.get(id);
        if(articleData == null){
            throw new Fault(new Exception("该文章不存在!"));
        }
        return new CxfArticleDetailResponse(articleData);
    }

	@Override
	public boolean msg_code(HeaderEntity header, String mobile) {
		WebServiceHeaderUtil.validateHeaderWithoutSession(header);
		String code = CxfMsgCodeUtils.getMsgCode(mobile);
		if(!TextUtils.isEmpty(code)){
			throw new Fault(new Exception("相同手机号一分钟内只能发送一次验证码"));
		}
		String msgCode = NoticeUtils.randomCode();
		Map param = new HashMap();
		param.put("code",msgCode);

		CxfMsgCodeUtils.setMsgCode(mobile,msgCode);
		try {
			NoticeUtils.forgetPasswdMsg(param,mobile);
		} catch (ClientException e) {
			e.printStackTrace();
			throw new Fault(new Exception("发送验证码失败"));
		}
		return true;
	}

	@Override
	public boolean forget_msg_code(HeaderEntity header, String loginName, String mobile) {
		WebServiceHeaderUtil.validateHeaderWithoutSession(header);
		CenterUser user;
		if(TextUtils.isEmpty(mobile)){
			user = centerService.getUserByLoginName(loginName);
		}else{
			user = centerService.getUserByMobile(mobile);
		}
		if(user==null || TextUtils.isEmpty(user.getMobile())){
			throw new Fault(new Exception("和户名或者手机号不存在"));
		}
		String code = CxfMsgCodeUtils.getMsgCode(user.getMobile());
		if(!TextUtils.isEmpty(code)){
			throw new Fault(new Exception("相同手机号一分钟内只能发送一次验证码"));
		}
		String msgCode = NoticeUtils.randomCode();
		Map param = new HashMap();
		param.put("code",msgCode);

		CxfMsgCodeUtils.setMsgCode(user.getMobile(),msgCode);
		try {
			NoticeUtils.forgetPasswdMsg(param,user.getMobile());
		} catch (ClientException e) {
			e.printStackTrace();
			throw new Fault(new Exception("发送验证码失败"));
		}
		return true;
	}

	@Override
	public int forget_pwd(HeaderEntity header, String loginName, String password, String mobile, String smgcode) {
		WebServiceHeaderUtil.validateHeaderWithoutSession(header);

		CenterUser user;
		if(TextUtils.isEmpty(mobile)){
			user = centerService.getUserByLoginName(loginName);
		} else{
			user = centerService.getUserByMobile(mobile);
		}
		if(user==null || TextUtils.isEmpty(user.getMobile())){
			throw new Fault(new Exception("和户名或者手机号不存在"));
		}

		String code = CxfMsgCodeUtils.getMsgCode(user.getMobile());
		if( !smgcode.equals(code) ){
			throw new Fault(new Exception("手机验证码不正确"));
		}
		if( TextUtils.isEmpty(password) ){
			throw new Fault(new Exception("新密码为空"));
		}
		user.setPassword(SystemService.entryptPassword(password));
		user.setUpdateDate(new Date());
		centerUserService.save(user);
		// 清除已经登陆的会话
		CxfSession session = cxfSessionService.getByUserName(user.getLoginName());
		if(session!=null){
			cxfSessionService.delete(session);
		}

		return 0;
	}

	@Override
	public int register(HeaderEntity header, String loginName, String password, String mobile, String smgcode) {
		WebServiceHeaderUtil.validateHeaderWithoutSession(header);

		CenterUser user = centerService.getUserByLoginName(loginName);
		if(user!=null){
			throw new Fault(new Exception("用户名已存在!"));
		}
		user = centerService.getUserByMobile(mobile);
		if(user!=null){
			throw new Fault(new Exception("手机号已注册!"));
		}
		if(TextUtils.isEmpty(smgcode)){
			throw new Fault(new Exception("验证码不可为空!"));
		}
		if(TextUtils.isEmpty(password)){
			throw new Fault(new Exception("密码不可为空!"));
		}
		String code = CxfMsgCodeUtils.getMsgCode(mobile);
		if(!smgcode.equals(code)){
			throw new Fault(new Exception("验证码不正确!"));
		}

		user = new CenterUser();
		user.setLoginName(loginName);
		user.setPassword(SystemService.entryptPassword(password));
		user.setMobile(mobile);
		user.setAuditFlag("1");
		centerUserService.save(user);
		if (TextUtils.isEmpty(user.getId()) ) {
			throw new Fault(new Exception("注册失败!"));
		}
		return 0;
	}

	@Override
	public boolean valid_username(HeaderEntity header, String loginName) {
		WebServiceHeaderUtil.validateHeaderWithoutSession(header);
		return centerService.getUserByLoginName(loginName)==null;
	}

	@Override
	public boolean valid_mobile(HeaderEntity header, String mobile) {
		WebServiceHeaderUtil.validateHeaderWithoutSession(header);
		return centerService.getUserByMobile(mobile)==null;
	}

	@Override
	public CxfResponse nbg_baseData(HeaderEntity header, String day) {
		WebServiceHeaderUtil.validateHeader(header);
		NbgBaseData nbgBaseData= new NbgBaseData();
		if(StringUtils.isEmpty(day)){
			day = String.format("%tF",new Date());
		}

		nbgBaseData.setRq(day);
		List  list = nbgBaseDataService.findList(nbgBaseData);
		CxfResponse result = new CxfResponse();
		result.setRet(true);
		result.setCount(list.size());
		result.setData(list);
		return result;
	}

	@Override
	public CxfResponse nbg_beixuan(HeaderEntity header, String day) {
		WebServiceHeaderUtil.validateHeader(header);
		if(StringUtils.isEmpty(day)){
			day = String.format("%tF",new Date());
		}
		NbgBeixuan nbgBaseData= new NbgBeixuan();
		nbgBaseData.setRq(day);
		List  list = nbgBeixuanService.findList(nbgBaseData);
		CxfResponse result = new CxfResponse();
		result.setRet(true);
		result.setCount(list.size());
		result.setData(list);
		return result;
	}

	@Override
	public CxfResponse nbg_fengko(HeaderEntity header, String day) {
		WebServiceHeaderUtil.validateHeader(header);
		if(StringUtils.isEmpty(day)){
			day = String.format("%tF",new Date());
		}
		NbgFengko nbgFengko= new NbgFengko();
		nbgFengko.setRq(day);
		List  list = nbgFengkoService.findList(nbgFengko);
		CxfResponse result = new CxfResponse();
		result.setRet(true);
		result.setCount(list.size());
		result.setData(list);
		return result;
	}

	@Override
	public CxfResponse nbg_fengkoDetail(HeaderEntity header, String fengkoId) {
		WebServiceHeaderUtil.validateHeader(header);
		NbgFengkoDetail nbgFengkoDetail= new NbgFengkoDetail();
		nbgFengkoDetail.setFengkoId(fengkoId);
		List  list = nbgFengkoDetailService.findList(nbgFengkoDetail);
		CxfResponse result = new CxfResponse();
		result.setRet(true);
		result.setCount(list.size());
		result.setData(list);
		return result;
	}

	@Override
	public CxfResponse nbg_juechechi(HeaderEntity header, String day) {
		WebServiceHeaderUtil.validateHeader(header);
		if(StringUtils.isEmpty(day)){
			day = String.format("%tF",new Date());
		}
		NbgJuechechi nbgJuechechi= new NbgJuechechi();
		nbgJuechechi.setRq(day);
		List  list = nbgJuechechiService.findList(nbgJuechechi);
		CxfResponse result = new CxfResponse();
		result.setRet(true);
		result.setCount(list.size());
		result.setData(list);
		return result;
	}

	@Override
	public CxfResponse nbg_ltyaogu(HeaderEntity header, String day) {
		WebServiceHeaderUtil.validateHeader(header);
		if(StringUtils.isEmpty(day)){
			day = String.format("%tF",new Date());
		}
		NbgLtyaogu nbgLtyaogu= new NbgLtyaogu();
		nbgLtyaogu.setRq(day);
		List  list = nbgLtyaoguService.findList(nbgLtyaogu);
		CxfResponse result = new CxfResponse();
		result.setRet(true);
		result.setCount(list.size());
		result.setData(list);
		return result;
	}

	@Override
	public CxfResponse nbg_zujichi(HeaderEntity header, String day) {
		WebServiceHeaderUtil.validateHeader(header);
		if(StringUtils.isEmpty(day)){
			day = String.format("%tF",new Date());
		}
		NbgZujichi nbgZujichi= new NbgZujichi();
		nbgZujichi.setRq(day);
		List  list = nbgZujichiService.findList(nbgZujichi);
		CxfResponse result = new CxfResponse();
		result.setRet(true);
		result.setCount(list.size());
		result.setData(list);
		return result;
	}

	@Override
	public CxfResponse xgb_ggxx(HeaderEntity header, String symbol) {
		WebServiceHeaderUtil.validateHeader(header);
		List<XgbHistoryData> list = new ArrayList<XgbHistoryData>();
		CxfResponse result = new CxfResponse();
		XgbBoardStock xgbBoardStock = new XgbBoardStock();
		xgbBoardStock.setSymbol(symbol);
		List<XgbBoardStock> xgbBoardStocks = xgbBoardStockService.findList(xgbBoardStock);
		XgbBoomStock xgbBoomStock = new XgbBoomStock();
		xgbBoomStock.setSymbol(symbol);
		List<XgbBoomStock> xgbBoomStocks = xgbBoomStockService.findList(xgbBoomStock);

		XgbBoardDown xgbBoardDown = new XgbBoardDown();
		xgbBoardDown.setSymbol(symbol);
		List<XgbBoardDown> xgbBoardDowns = xgbBoardDownService.findList(xgbBoardDown);

		for (XgbBoardStock bs : xgbBoardStocks ) {
			XgbHistoryData xgbHistoryData = new XgbHistoryData();
			xgbHistoryData.setContinueBoardCount(bs.getContinueBoardCount());
			xgbHistoryData.setDay(bs.getDay());
			xgbHistoryData.setReason(bs.getReason());
			xgbHistoryData.setSymbol(bs.getSymbol());
			xgbHistoryData.setTitle(bs.getTitle());
			xgbHistoryData.setTime(bs.getLastRaiseTime());
			xgbHistoryData.setCurPrice(bs.getCurPrice());
			xgbHistoryData.setPxChangeRate(bs.getPxChangeRate());
			xgbHistoryData.setType("涨停板");
			list.add(xgbHistoryData);
		}

		for (XgbBoomStock bs : xgbBoomStocks ) {
			XgbHistoryData xgbHistoryData = new XgbHistoryData();
			xgbHistoryData.setContinueBoardCount(bs.getContinueBoardCount());
			xgbHistoryData.setDay(bs.getDay());
			xgbHistoryData.setReason(bs.getReason());
			xgbHistoryData.setSymbol(bs.getSymbol());
			xgbHistoryData.setTitle(bs.getTitle());
			xgbHistoryData.setTime(bs.getLastBoomTime());
			xgbHistoryData.setCurPrice(bs.getCurPrice());
			xgbHistoryData.setPxChangeRate(bs.getPxChangeRate());
			xgbHistoryData.setType("被砸开板");
			list.add(xgbHistoryData);
		}


		for (XgbBoardDown bs : xgbBoardDowns ) {
			XgbHistoryData xgbHistoryData = new XgbHistoryData();
			xgbHistoryData.setContinueBoardCount(bs.getContinueBoardCount());
			xgbHistoryData.setDay(bs.getDay());
			xgbHistoryData.setReason(bs.getReason());
			xgbHistoryData.setSymbol(bs.getSymbol());
			xgbHistoryData.setTitle(bs.getTitle());
			xgbHistoryData.setTime(bs.getLastBoardTime());
			xgbHistoryData.setCurPrice(bs.getCurPrice());
			xgbHistoryData.setPxChangeRate(bs.getPxChangeRate());
			xgbHistoryData.setType("跌停板");
			list.add(xgbHistoryData);
		}

		Collections.sort(list, new Comparator<XgbHistoryData>() {
			@Override
			public int compare(XgbHistoryData o1, XgbHistoryData o2) {
				return o1.getDay().compareTo(o2.getDay());
			}
		});

		result.setRet(true);
		result.setCount(list.size());
		result.setData(list);
		return result;
	}

}
